package kr.ac.chungbuk;

import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	IBoardDAO ibaties = new IBoardDAO();
	ArrayList<ItemDTO> list = new ArrayList<ItemDTO>();
	ArrayList<UserDTO> userList=new ArrayList<UserDTO>();
	SaleDTO sale = new SaleDTO();
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
		
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		
		String formattedDate = dateFormat.format(date);
		
		model.addAttribute("serverTime", formattedDate );
		
		return "home";
	}
	@RequestMapping(value="index", method = RequestMethod.GET)
	 public ModelAndView handleRequest(HttpServletRequest requset, HttpServletResponse response,HttpSession session){
	  list=(ArrayList<ItemDTO>)ibaties.selectAll();
	  ModelAndView modelAndView =new ModelAndView();
	  modelAndView.setViewName("../views/index/index");
	  UserDTO user = (UserDTO) session.getAttribute("user");
		if(user!=null){
			modelAndView.addObject("user",user);
		}
	  modelAndView.addObject("itemList",list);

	  return modelAndView;
	 }
	@RequestMapping("logout")
	public String logout(HttpSession session){
		session.invalidate();
		return "redirect:index";
	}
	@RequestMapping("index")
	public String index(){
		return "../views/index/index";
	}
	@RequestMapping("jsp_header")
	public String jsp_header(){
		
		return "jsp_header";
	}
	@RequestMapping("cart_header")
	public String cart_header(){
		return "cart_header";
	}
	@RequestMapping("detail")
	 public ModelAndView handleDetail(int item_ID,HttpSession session){
		ItemDTO item= new ItemDTO();
		item=ibaties.selectOne(item_ID);
		ModelAndView mav = new ModelAndView();
		mav.setViewName("detail");
		UserDTO user = (UserDTO) session.getAttribute("user");
		if(user!=null){
			mav.addObject("user",user);
		}
		mav.addObject("item",item);
		
		return mav;
	}
	@RequestMapping("login")
	public String login(){
		return "../views/loginform/login";
	}
	@RequestMapping("loginSuccess")
	public String loginSuccess(){
			
		return "../views/loginform/loginSuccess";
	}
	@RequestMapping(value="loginProcess",method=RequestMethod.POST)
	public ModelAndView login(ModelAndView mav,String user_id, String passwd,HttpServletRequest request){
		UserDTO user=ibaties.selectTwo(user_id);
		
		if(user==null){
			System.out.println("사용자 아이디값이 없습니다.");
			mav.setViewName("login");
		}else{
			System.out.println("id사용자아이디는"+user.getUser_id());
				
			if(passwd.equals(user.getPasswd())){
				request.getSession().setAttribute("user",user);
			}else{
				System.out.println("패스워드가 틀립니다.");
			}
			mav.addObject("user",user);
			mav.setViewName("../views/loginform/loginSuccess");
			}
		return mav;
	}
	@RequestMapping("userEntry")
	public String userEntry(){
		return "../views/userentryform/userEntry";
	}
	@RequestMapping("userEntrySuccess")
	public String userEntrySuccess(){
		return "../views/userentryform/userEntrySuccess";
	}
	@RequestMapping(value="insertProc",method=RequestMethod.GET)
	public ModelAndView insertProc(ModelAndView mav,UserDTO user){
				
		ibaties.insertUser(user);
		mav.addObject("insertuser", user);
		mav.setViewName("../views/userentryform/userEntrySuccess");
				
		return mav;
	}
	@RequestMapping("execption")
	public String exception(){
		return "exception";
	}
	@RequestMapping("cart")
	public String cart(){
		return "../views/cart/cart";
	}
	@RequestMapping(value="cartAdd")
	public ModelAndView cartAdd(Integer item_ID,Integer quantity,HttpSession session){
		ItemDTO selectedItem = ibaties.selectOne(item_ID);
		System.out.println(selectedItem.getItem_Name());
		ItemSet itemset= new ItemSet(selectedItem,quantity);
		
		Cart cart =new Cart();
		
		if(session.getAttribute("cartList")!=null){
			cart=(Cart)session.getAttribute("cartList");
		}
		cart.push(itemset);
		session.setAttribute("cartList", cart);
		
		ModelAndView mav=new ModelAndView();
		mav.setViewName("../views/cart/cart");
		mav.addObject("message",selectedItem.getItem_Name()+"을(를)"+quantity+"개 카트에 추가했습니다.");
		mav.addObject("cart",cart);
		
		UserDTO user = (UserDTO) session.getAttribute("user");
		if(user!=null){
			mav.addObject("user",user);
		}
		return mav;
	}
	@RequestMapping(value="cartClear")
	public ModelAndView cartClear(HttpSession session){
		Cart cart = new Cart();
		cart=null;
		
		session.setAttribute("cartList", cart);
		
		ModelAndView mav=new ModelAndView();
		mav.setViewName("../views/cart/cart");
		mav.addObject("message","카트를 비웠습니다.");
		
		UserDTO user = (UserDTO) session.getAttribute("user");
		if(user!=null){
			mav.addObject("user",user);
		}
		return mav;
	}
	@RequestMapping(value="cartConfirm")
	public ModelAndView cartConfirm(HttpSession session){
		Cart cart = (Cart)session.getAttribute("cartList");
		if(cart==null){
			session.setAttribute("cartList", cart);
		}
		ModelAndView mav= new ModelAndView();
		mav.setViewName("../views/cart/cart");
		mav.addObject("cart",cart);
		UserDTO user = (UserDTO) session.getAttribute("user");
		if(user!=null){
			mav.addObject("user",user);
		}
		return mav;
		
	}
	@RequestMapping("checkout")
	public ModelAndView checkout(HttpSession session){
		ModelAndView mav = new ModelAndView();
		
		UserDTO user=(UserDTO)session.getAttribute("user");
		if(user==null){
			mav.setViewName("../views/loginform/login");
			return mav;
		}
		
		Cart cart = (Cart)session.getAttribute("cartList");
		if(cart==null||cart.isEmpty()){
			mav.setViewName("redirect:cartConfirm");
			return mav;
		}
		
		mav.addObject("user",user);
		List<ItemSet> itemList=cart.getItemList();
		mav.addObject("itemList",itemList);
		
		Integer totalAmount = calculateTotalAmout(itemList);
		mav.addObject("totalAmount",totalAmount);
		mav.setViewName("../views/checkout/checkout");
		
		return mav;
		
				
	}
	public Integer calculateTotalAmout(List<ItemSet> itemList){
		int totalAmount =0;
		
		for(ItemSet itemSet:itemList){
			int price=itemSet.getItem().getPrice().intValue();
			int quantity=itemSet.getQuantity().intValue();
			totalAmount=totalAmount+(price*quantity);
		}
		return new Integer(totalAmount);
	}
	@RequestMapping("end")
	public ModelAndView end(HttpSession session){
		ModelAndView mav= new ModelAndView();
		
		UserDTO user=(UserDTO)session.getAttribute("user");
		
		if(user==null){
			mav.setViewName("../views/loginform/login");
		}
		
		Cart cart=(Cart)session.getAttribute("cartList");
		
		if(cart==null||cart.isEmpty()){
			mav.setViewName("../views/cart/cart");
		}
		System.out.println(user.getUser_id());
		
		createSale(user, cart);
		ibaties.insertSale(sale);
		for(SaleLineDTO saleline:sale.getSaleLineList()){
			ibaties.insertSaleLine(saleline);
		}
		cart.clearAll();
		mav.addObject("user",user);
		mav.setViewName("../views/end/end");
		return mav;
		
	}
	private SaleDTO createSale(UserDTO user,Cart cart){
		sale.setSale_id(ibaties.findMaxSaleId()+1);
		sale.setUser_id(user.getUser_id());
		Timestamp currentTime=getCurrentTime();
		sale.setUpdate_time(currentTime);
		
		List<ItemSet> itemList=cart.getItemList();
		for(int i=0;i<itemList.size();i++){
			ItemSet itemSet=(ItemSet)itemList.get(i);
			
			int sale_line_id=i+1;
			SaleLineDTO saleline=createSaleLine(sale, sale_line_id, itemSet, currentTime);
			sale.addSaleLine(saleline);
		}
		return sale;
	}
	private SaleLineDTO createSaleLine(SaleDTO sale,int sale_line_id,ItemSet itemset,Timestamp currentTime){
		return new SaleLineDTO(sale.getSale_id(),new Integer(sale_line_id),itemset.getItem().getItem_ID(),currentTime,itemset.getQuantity());
	}
	private Timestamp getCurrentTime(){
		return new Timestamp(Calendar.getInstance().getTimeInMillis());
	}
}


